<template>
  <div class="goods-detail-container">
    <!-- 返回按钮 -->
    <button class="back-btn" @click="goBack">
      <i class="icon-arrow-left"></i> 返回列表
    </button>


    <!-- 商品详情 -->
    <div v-if="goodsItem" class="detail-content">
      <!-- 商品图片和信息 -->
      <div class="goods-main">
        <div class="goods-image">
          <img :src="goodsItem.image_url" alt="商品图片" @error="handleImageError">
        </div>

        <div class="goods-info">
          <h1 class="goods-title">{{ goodsItem.prod_name }}</h1>

          <div class="goods-price">
            <span class="price-label">售价：</span>
            <span class="price-value">¥{{ goodsItem.price }}</span>
          </div>

          <div class="goods-sales">
            <span class="sales-label">库存:</span>
            <span class="sales-value">{{ goodsItem.store }} 件</span>
          </div>

          <!-- 购买数量选择框 -->
          <div class="goods-quantity">
            <span class="quantity-label">购买数量：</span>
            <div class="quantity-control">
              <!-- 减少数量按钮 -->
              <button
                  class="quantity-btn minus-btn"
                  @click="handleMinus"
                  :disabled="buyQuantity <= 1"
              >
                -
              </button>
              <!-- 数量输入框 -->
              <input
                  type="number"
                  v-model.number="buyQuantity"
                  class="quantity-input"
                  :min="1"
                  :max="goodsItem.store"
                  readonly
              ><!-- 只展示不修改-->
              <!-- 增加数量按钮 -->
              <button
                  class="quantity-btn plus-btn"
                  @click="handlePlus"
                  :disabled="buyQuantity >= goodsItem.store"
              >
                +
              </button>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="action-buttons">
            <button class="add-cart-btn" @click="addToCart">
              <i class="icon-cart"></i> 加入购物车
            </button>
            <button class="buy-now-btn" @click="buyNow">
              立即购买
            </button>
          </div>
        </div>
      </div>

      <!-- 商品描述 -->
      <div class="goods-description">
        <h2 class="desc-title">商品详情</h2>
        <div class="desc-content">
          {{ goodsItem.prod_desc }}
        </div>
      </div>
    </div>

    <!-- 商品不存在 -->
    <div v-else class="not-found">
      商品不存在或已下架
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import ProductApi from "@/api/Product.js";
import defaultImage from '@/assets/图片加载失败.png';
import CartApi from '@/api/cart.js'
import {ElMessage} from "element-plus";
// 路由实例
const router = useRouter();

// 状态管理
const goodsItem = ref({});
const isLoading = ref(true); // 加载状态
const buyQuantity = ref(1); // 购买数量，默认1件
const cartItem = ref({});
const firstPrice=ref();  //记录商品原始价格
// 页面加载时获取商品详情
onMounted(async () => {
  try {
    const productId = router.currentRoute.value.query.id;
    if (!productId) {
      return;
    }
    goodsItem.value = await ProductApi.getProductInfo(productId);
    firstPrice.value=goodsItem.value.price;
    // 确保购买数量不超过初始库存
    if (buyQuantity.value > goodsItem.value.store) {
      buyQuantity.value = goodsItem.value.store;
    }
  } catch (error) {
    console.error('获取商品详情失败：', error);
    goodsItem.value = {};
  } finally {
    isLoading.value = false; // 结束加载
  }
});

// 处理图片加载失败
const handleImageError = (e) => {
  e.target.src = defaultImage;
};

// 返回商品列表页
const goBack = () => {
  router.push('/main');
};

// 新增：减少购买数量
const handleMinus = () => {
  if (buyQuantity.value > 1) {
    buyQuantity.value--;
    goodsItem.value.price = firstPrice.value * buyQuantity.value;
  }
};

//增加购买数量
  const handlePlus = async() => {
    // 先校验库存是否有效（防止商品无库存时异常）
    if (!goodsItem.value?.store || goodsItem.value.store <= 0) {
      ElMessage.warning('当前商品暂无库存，无法增加数量');
      return;
    }
    let count = await CartApi.getProductCount(goodsItem.value.id);
    if(count+buyQuantity.value>await ProductApi.getStore(goodsItem.value.id)){
      ElMessage.error('购物车商品数量超出库存限制');
      return;
    }
    // 数量未超过库存时才允许增加
    if (buyQuantity.value < goodsItem.value.store) {
      buyQuantity.value++;
      // 同步更新商品总价（单价×数量）
      goodsItem.value.price = firstPrice.value * buyQuantity.value;
    } else {
      // 超过库存时提示具体限制
      ElMessage.warning(`库存不足，最多可购买 ${goodsItem.value.store} 件`);
    }
  };


// 加入购物车（更新：携带选择的数量）
const addToCart = async () => {
  if (!goodsItem.value) return;
  if (goodsItem.value.store===0) {
    ElMessage.error('商品数量不足，请选择其他商品');
    return;
  }
  if (await CartApi.getProductCount(goodsItem.value.id) + buyQuantity.value > await ProductApi.getStore(goodsItem.value.id)) {
    ElMessage.error('购物车商品数量超出库存限制');
    return;
  }


  cartItem.value = {
    prod_id: goodsItem.value.id,
    prod_name: goodsItem.value.prod_name,
    prod_price: firstPrice.value, // 与模板商品价格一致
    image_url: goodsItem.value.image_url,
    count: buyQuantity.value, // 改用选择的数量
    money: goodsItem.value.price,
  };

  // 提示中显示选择的数量
  ElMessage.success(`已将【${goodsItem.value.prod_name}】×${buyQuantity.value} 加入购物车`);
  await CartApi.addToCart(cartItem.value);
};

// 立即购买（更新：携带选择的数量）
const buyNow = () => {
  if (!goodsItem.value || !goodsItem.value.id) {
    ElMessage.error('商品信息无效，无法购买');
    return;
  }
  if (goodsItem.value.store===0){
    ElMessage.error('商品数量不足，请选择其他商品');
    return;
  }

  // 核心：把单个商品对象放进数组中（[商品对象]）
  const cartDataArray = [
    {
      // 复制订单页需要的字段（与购物车选中商品格式保持一致）
      prod_id: goodsItem.value.id,
      prod_name: goodsItem.value.prod_name,
      prod_price: firstPrice.value, // 单价（原始价格）
      image_url: goodsItem.value.image_url,
      count: buyQuantity.value, // 选择的购买数量
      // 其他订单页可能需要的字段（根据订单页逻辑补充）
    }
  ];

  try {
    // 序列化数组并传递（与购物车跳转逻辑保持一致）
    const cartDataStr = encodeURIComponent(JSON.stringify(cartDataArray));

    // 跳转订单页，参数格式与购物车跳转完全相同
    router.push({
      path: '/order',
      query: { cartData: cartDataStr }
    });

    ElMessage.success(`准备购买【${goodsItem.value.prod_name}】×${buyQuantity.value}`);
  } catch (error) {
    console.error('跳转订单页失败：', error);
    ElMessage.error('跳转失败，请重试');
  }
};
</script>

<style scoped>
/* 原有样式不变，新增/补充以下样式 */
.goods-detail-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  box-sizing: border-box;
}

.back-btn {
  display: inline-flex;
  align-items: center;
  margin-bottom: 20px;
  padding: 8px 16px;
  background-color: #f5f5f5;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  color: #333;
  transition: background-color 0.2s;
}

.back-btn:hover {
  background-color: #e0e0e0;
}

.icon-arrow-left::before {
  content: '←';
  margin-right: 5px;
}

/* 加载状态样式 */
.loading, .not-found {
  text-align: center;
  padding: 50px 0;
  font-size: 18px;
  color: #666;
}

.detail-content {
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.goods-main {
  display: flex;
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.goods-image {
  flex: 0 0 400px;
  margin-right: 30px;
}

.goods-image img {
  width: 100%;
  height: auto;
  border-radius: 8px;
}

.goods-info {
  flex: 1;
}

.goods-title {
  font-size: 24px;
  color: #333;
  margin: 0 0 20px;
  line-height: 1.4;
}

.goods-price {
  margin: 0 0 15px;
  padding: 10px 0;
  border-bottom: 1px dashed #eee;
}

.price-label {
  color: #666;
  font-size: 14px;
}

.price-value {
  color: #ff6700;
  font-size: 28px;
  font-weight: bold;
  margin-left: 10px;
}

.goods-sales {
  margin: 0 0 15px; /* 调整间距，为数量选择框腾出位置 */
  color: #666;
  font-size: 14px;
}

.sales-value {
  color: #ff6700;
  margin-left: 5px;
}

/* 新增：购买数量选择框样式 */
.goods-quantity {
  margin: 0 0 30px;
  display: flex;
  align-items: center;
}

.quantity-label {
  color: #666;
  font-size: 14px;
  margin-right: 12px;
  white-space: nowrap;
}

.quantity-control {
  display: flex;
  align-items: center;
  border: 1px solid #ddd;
  border-radius: 4px;
  overflow: hidden;
}

.quantity-btn {
  width: 36px;
  height: 36px;
  border: none;
  background-color: #f5f5f5;
  color: #333;
  cursor: pointer;
  font-size: 18px;
  transition: background-color 0.2s;
}

.quantity-btn:hover {
  background-color: #e8e8e8;
}

.quantity-btn:disabled {
  color: #ccc;
  cursor: not-allowed;
  background-color: #fafafa;
}

.quantity-input {
  width: 60px;
  height: 36px;
  border: none;
  border-left: 1px solid #ddd;
  border-right: 1px solid #ddd;
  text-align: center;
  font-size: 14px;
  outline: none;
}

.quantity-input:focus {
  box-shadow: inset 0 0 0 1px #ff6700;
}

.goods-spec {
  margin: 0 0 30px;
}

.spec-label {
  display: inline-block;
  width: 80px;
  color: #666;
  font-size: 14px;
  vertical-align: top;
}

.spec-options {
  display: inline-block;
}

.spec-item {
  display: inline-block;
  padding: 8px 16px;
  margin-right: 10px;
  margin-bottom: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}

.spec-item:hover {
  border-color: #ff6700;
}

.spec-item.active {
  border-color: #ff6700;
  background-color: rgba(255, 103, 0, 0.1);
  color: #ff6700;
}

.action-buttons {
  display: flex;
  gap: 20px;
  margin-top: 10px; /* 微调间距 */
}

.add-cart-btn, .buy-now-btn {
  padding: 12px 0;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  flex: 1;
}

.add-cart-btn {
  background-color: #fff;
  border: 1px solid #ff6700;
  color: #ff6700;
}

.add-cart-btn:hover {
  background-color: rgba(255, 103, 0, 0.1);
}

.icon-cart::before {
  content: '🛒';
  margin-right: 5px;
}

.buy-now-btn {
  background-color: #ff6700;
  color: #fff;
}

.buy-now-btn:hover {
  background-color: #e05a00;
}

.goods-description {
  padding: 20px;
}

.desc-title {
  font-size: 20px;
  color: #333;
  margin: 0 0 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.desc-content {
  color: #666;
  line-height: 1.8;
  font-size: 16px;
}

/* 响应式适配：调整数量选择框在小屏幕的显示 */
@media (max-width: 992px) {
  .goods-main {
    flex-direction: column;
  }

  .goods-image {
    flex: none;
    width: 100%;
    max-width: 400px;
    margin: 0 auto 20px;
  }
}

@media (max-width: 576px) {
  .action-buttons {
    flex-direction: column;
    gap: 10px;
  }

  .goods-title {
    font-size: 20px;
  }

  .price-value {
    font-size: 24px;
  }

  /* 小屏幕调整数量选择框宽度 */
  .quantity-input {
    width: 50px;
  }
}
</style>